<template>
  <view class="consultation-edit-container">
    <view class="page-header">
      <text class="page-title">编辑问诊</text>
      <text class="page-subtitle">医生回复问诊</text>
    </view>

    <view v-if="pageLoading" class="page-loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载数据中...</text>
    </view>

    <view v-else class="form-container">
      <view class="form-section readonly-section">
        <text class="section-title">问诊信息</text>
        
        <view class="info-row">
          <text class="info-label">患者ID：</text>
          <text class="info-value">{{ formData.patient_id }}</text>
        </view>
        
        <view class="info-row">
          <text class="info-label">医生ID：</text>
          <text class="info-value">{{ formData.doctor_id }}</text>
        </view>
        
        <view class="info-row vertical">
          <text class="info-label">患者问题：</text>
          <text class="info-value">{{ formData.question }}</text>
        </view>
        
        <view v-if="formData.attachments && formData.attachments.length > 0" class="info-row vertical">
          <text class="info-label">附件：</text>
          <view class="attachments-list">
            <view v-for="(file, index) in formData.attachments" :key="index" class="attachment-item">
              <text class="attachment-name">附件{{ index + 1 }}</text>
            </view>
          </view>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">医生回复</text>
        
        <view class="form-item">
          <text class="form-label required">回复内容</text>
          <textarea 
            v-model="formData.answer" 
            class="form-textarea" 
            placeholder="请输入您的专业建议和回复"
            maxlength="2000"
          />
          <text v-if="errors.answer" class="error-text">{{ errors.answer }}</text>
        </view>

        <view class="form-item">
          <text class="form-label">问诊状态</text>
          <radio-group @change="onStatusChange" class="radio-group">
            <label class="radio-item">
              <radio value="0" :checked="formData.status === 0" color="#007aff"/>
              <text class="radio-text">待回复</text>
            </label>
            <label class="radio-item">
              <radio value="1" :checked="formData.status === 1" color="#007aff"/>
              <text class="radio-text">已回复</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.status === 2" color="#007aff"/>
              <text class="radio-text">已结束</text>
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const pageLoading = ref(true)
const consultationId = ref('')

const formData = reactive({
  patient_id: '',
  doctor_id: '',
  question: '',
  attachments: [],
  answer: '',
  status: 0
})

const errors = reactive({
  answer: ''
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  consultationId.value = currentPage.options.id || ''
  
  if (!consultationId.value) {
    uni.showToast({ title: '缺少问诊ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/consultations/list' })
    }, 1500)
    return
  }
  
  await loadConsultationData()
  pageLoading.value = false
})

async function loadConsultationData() {
  try {
    // 调用云对象方法获取问诊信息
    const consultationsObj = uniCloud.importObject('dh-consultations')
    const result = await consultationsObj.getConsultationById(consultationId.value)
    
    if (result.code === 200 && result.data) {
      Object.assign(formData, result.data)
    } else {
      throw new Error(result.message || '问诊记录不存在')
    }
  } catch (err) {
    console.error('加载问诊数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/consultations/list' })
    }, 1500)
  }
}

function onStatusChange(e) {
  formData.status = parseInt(e.detail.value)
}

function validateForm() {
  let isValid = true
  
  if (formData.status === 1 && (!formData.answer || formData.answer.trim().length === 0)) {
    errors.answer = '状态为已回复时必须填写回复内容'
    isValid = false
  } else {
    errors.answer = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '保存中...' })
    
    const db = uniCloud.database()
    const submitData = {
      answer: formData.answer,
      status: formData.status,
      answer_time: formData.answer ? Date.now() : null,
      update_time: Date.now()
    }
    
    // 调用云对象方法更新咨询
    const consultationsObj = uniCloud.importObject('dh-consultations')
    const result = await consultationsObj.updateConsultation(consultationId.value, submitData)
    
    uni.hideLoading()
    
    if (result.code === 200) {
      uni.showToast({ title: result.message || '更新成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/consultations/list' })
      }, 1500)
    } else {
      uni.showToast({ title: '更新失败', icon: 'none' })
    }
  } catch (err) {
    console.error('更新失败:', err)
    uni.hideLoading()
    uni.showToast({ title: err.message || '更新失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/consultations/list' })
}
</script>

<style lang="scss" scoped>
.consultation-edit-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.page-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  background: #fff;
  border-radius: 16rpx;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.readonly-section {
  background: #f8f9fa;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.info-row {
  display: flex;
  margin-bottom: 20rpx;
  
  &.vertical {
    flex-direction: column;
  }
}

.info-label {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}

.attachments-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
  margin-top: 12rpx;
}

.attachment-item {
  padding: 12rpx 24rpx;
  background: #e3f2fd;
  color: #1976d2;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.form-textarea {
  width: 100%;
  min-height: 300rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}
</style>
